<?php
function connect() {
    $link = @mysqli_connect('127.0.0.1:2483', 'root', 'root', 'world');
    if ($error = mysqli_connect_errno()) {
        trigger_error(sprintf("DB > Error de conexión: #%s - %s\n", $error, mysqli_connect_error()), E_USER_ERROR);
        return null;
    }
    mysqli_set_charset($link, 'utf8');
    return $link;
}


function get_cities_details_traditional_style($link) {
   $query = <<<SQL
    SELECT
        c.Name as CityName, c.District, c.Population,
        ct.Name as CountryName, ct.Continent, ct.Region
    FROM
        city c
        INNER JOIN country ct ON c.CountryCode = ct.Code
    LIMIT 10
SQL;

    $rows = [];
    if ($result = mysqli_query($link, $query)) {
        $count = mysqli_num_rows($result);
        /**
         * Obtener filas en un arreglo asociativo
         */
        $i = 0;
        while ($row = mysqli_fetch_assoc($result)) {
            dump_to_console(sprintf('BD > Obteniendo detalles de la fila: %u from %u', ++$i, $count));
            $rows[] = $row;
        }

        /**
         * Libera la memoria de los resultados asociados con la sentencia
         */
        mysqli_free_result($result);
    } elseif ($error = mysqli_error($link)) {
        trigger_error(sprintf("Error de SQL: #%s - %s\n", $error, mysqli_error($link)), E_USER_ERROR);
    }

    return $rows;
}

function get_cities_details_using_generator($link) {
    $query = <<<SQL
    SELECT
        c.Name as CityName, c.District, c.Population,
        ct.Name as CountryName, ct.Continent, ct.Region
    FROM
        city c
        INNER JOIN country ct ON c.CountryCode = ct.Code
    LIMIT 10
SQL;
    if ($result = mysqli_query($link, $query)) {
        $count = mysqli_num_rows($result);
        /**
         * Obtener filas en un arreglo asociativo
         */
        $i = 0;
        while ($row = mysqli_fetch_assoc($result)) {
            dump_to_console(sprintf('BD > Obteniendo detalles de la fila: %u de %u', ++$i, $count));
            yield $row;
        }

        /**
         * Libera la memoria de los resultados asociados con la sentencia
         */
        mysqli_free_result($result);
    } elseif ($error = mysqli_error($link)) {
        trigger_error(sprintf("Error de SQL: #%s - %s\n", $error, mysqli_error($link)), E_USER_NOTICE);
    }
}


/**
 * Cierro la conexión
 */
function close_connection($link) {
    mysqli_close($link);
}

/*
 * Muestra un mensaje en la consola del Browser: Chromium o FF
 */
function dump_to_console($message) {
    echo "<script>console.log('$message');</script>";
}
